# -*- coding: utf-8 -*-
# @Time    : 2021/10/21
# @Author  : CHENlj
# @File    : Compression.py

"""
封装压缩库
"""
import os, zipfile

from Common.Log import Mylog


class Compression:

    def toZip(self, start_dir):
        """
        压缩文件夹
        :param start_dir: 需要压缩的文件夹路径
        :return:
        """
        base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        zip_dir = os.path.join(base_dir, 'Zip')
        try:
            file_news = os.path.join(zip_dir, 'report.zip')  # 压缩后文件的名字
            print(file_news)
            z = zipfile.ZipFile(file_news, 'w', zipfile.ZIP_DEFLATED)  # 参数一：文件夹名
            # 遍历文件夹，返回文件夹本身路径、文件夹中所有目录的名字（列表）、文件夹中所有文件的名字（列表）
            for dirpath, dirnames, filenames in os.walk(start_dir):
                fpath = dirpath.replace(start_dir, '')
                fpath = fpath and fpath + os.sep or ''
                for filename in filenames:
                    z.write(os.path.join(dirpath, filename), fpath + filename)
            print('压缩成功')
            z.close()
            return file_news

        except:
            print("压缩失败")
            Mylog.error("压缩失败")


if __name__ == '__main__':
    # start_dir = r'../Report'
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    start_dir = os.path.join(BASE_DIR, 'Report')
    comp = Compression()
    comp.toZip(start_dir)


